package com.ebix.sample.dao.helper;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

/**
 * we use a enum for singleton purposes. by far better that private constructor
 * 
 * @author Ebix L.A.
 * 
 */
public enum DAOHelper {

	INSTANCE;

	/**
	 * signature to recover the database access
	 * 
	 * @return a connection
	 * @throws NamingException
	 * @throws SQLException
	 */
	public Connection getConnection() throws NamingException, SQLException {
		DataSource ds = (DataSource) new InitialContext()//
				.lookup("java:comp/env/jdbc/wisng-ds");
		return ds.getConnection();
	}

	/**
	 * some heper funcions to close the datasource objects
	 * 
	 * @param con
	 * @param st
	 * @param rs
	 */
	public void close(Connection con, Statement st, ResultSet rs) {
		try {
			if (rs != null)
				rs.close();
			if (st != null)
				st.close();
			if (con != null)
				con.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * some heper funcions to close the datasource objects
	 * 
	 * @param con
	 * @param st
	 */
	public void close(Connection con, Statement st) {
		close(con, st, null);
	}

	/**
	 * 
	 * some heper funcions to close the datasource objects
	 * 
	 * @param st
	 * @param rs
	 */
	public void close(Statement st, ResultSet rs) {
		close(null, st, rs);
	}

	/**
	 * 
	 * some heper funcions to close the datasource objects
	 * 
	 * @param st
	 */
	public void close(Statement st) {
		close(null, st, null);
	}

	/**
	 * 
	 * some heper funcions to close the datasource objects
	 * 
	 * @param rs
	 */
	public void close(ResultSet rs) {
		close(null, null, rs);
	}

}
